﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using LeoShi.Soft.OpenSinaAPI;
using System.IO;
using TCS.DBUtility;


namespace TCS.Web.MembersHome
{
    public partial class publish : System.Web.UI.Page
    {
        private string PicPath
        {
            get { return (string)ViewState["PicPath"]; }
            set { ViewState["PicPath"] = value; }
        }
        private string PicPath1
        {
            get { return (string)ViewState["PicPath1"]; }
            set { ViewState["PicPath1"] = value; }
        }
        private int PageIndex
        {
            get { return (int)ViewState["PageIndex"]; }
            set { ViewState["PageIndex"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Ajax.Utility.RegisterTypeForAjax(typeof(publish));
            //this.rdoPublic1.Checked=true;
            if (!Page.IsPostBack)
            {

                ViewState["PicPath"] = "";
                ViewState["PicPath1"] = "";
                ViewState["PageIndex"] = 1;
                BindWaitInfo();
                BindEmotion(); //绑定表情
            }

        }
        /// <summary>
        /// 绑定待发微博
        /// </summary>
        private void BindWaitInfo()
        {

            TCS.Model.MemberInfo memberInfo = (TCS.Model.MemberInfo)Session["BangShangMember"];
            Session["WaitInfoSearch"] = " where SendStatus=0 and CreateMemgerID=" + memberInfo.Id;
            DataSet ds = GetPageMore(PageIndex, 5, Session["WaitInfoSearch"].ToString());
            rptWaitInfo.DataSource = ds;
            rptWaitInfo.DataBind();
        }
        private void BindSearchWaitInfo(string searchSql)
        {
            TCS.Model.MemberInfo memberInfo = (TCS.Model.MemberInfo)Session["BangShangMember"];
            DataSet ds = GetPageMore(PageIndex, 5, Session["WaitInfoSearch"].ToString());
            rptWaitInfo.DataSource = ds;
            rptWaitInfo.DataBind();
        }
        protected void btnPublish_Click(object sender, EventArgs e)
        {
            if (this.txtText.Value.Trim()== "")
            {
                return;
            }
            if(this.hidValue.Value!="")
            {
              
            }
            TCS.Model.MemberInfo memberInfo = (TCS.Model.MemberInfo)Session["BangShangMember"];
            TCS.BLL.Weibo.WeiBo_WaitInfo waitInfoAdd = new TCS.BLL.Weibo.WeiBo_WaitInfo();
            int result = -1;

            TCS.Model.Weibo.WeiBo_WaitInfo waitInfo = new TCS.Model.Weibo.WeiBo_WaitInfo();  //待发微博
            waitInfo.Content = txtText.Value.ToString();
            waitInfo.CreateDate = DateTime.Now;
            waitInfo.CreateMemgerID = memberInfo.Id;
            waitInfo.SendStatus = 0;  //0为未发送
            waitInfo.Picture = ViewState["PicPath"].ToString();      //虚拟路径
            waitInfo.Picture1 = ViewState["PicPath1"].ToString();  //物理路径
            waitInfo.LocalUrl ="";
            waitInfo.SendDate = DateTime.Now;          //设置的发送时间

            if (rdoPublic.Checked ==false)      //定时发布
            {
                result = waitInfoAdd.Add(waitInfo);          //添加待发微博
                if (result > 0)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('添加定时发布成功！');location.href='publish.aspx';</script>");
                }
                else
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('添加失败！');location.href='publish.aspx';</script>");
                }
            }else      //立即发布
            {
                if (ViewState["PicPath"].ToString()=="")  //文字微博
                {
                    var httpRequest1 = HttpRequestFactory.CreateHttpRequest(Method.POST);
                    httpRequest1.Token = Session["oauth_token"].ToString();
                    httpRequest1.TokenSecret = Session["oauth_token_secret"].ToString();
                    httpRequest1.UserRemoteIP = Request.UserHostAddress;
                    var url1 = "http://api.t.sina.com.cn/statuses/update.xml?";
                    httpRequest1.Request(url1, "status=" + HttpUtility.UrlEncode(txtText.Value));
               } else
                {
                    var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST) as HttpPost;
                    httpRequest.Token = Session["oauth_token"].ToString();
                    httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
                    httpRequest.UserRemoteIP = Request.UserHostAddress;
                    string basic = "http://api.t.sina.com.cn/";
                    string url = "";
                    string content =this.txtText.Value.ToString();
                    url = basic + "statuses/upload.xml";
                    string filePath = ViewState["PicPath1"].ToString();
                    httpRequest.RequestWithPicture(url, "status=" + HttpUtility.UrlEncode(content), filePath);
                   }

            }

        }
        protected void LinkEdit_Click(object sender, EventArgs e)
        {

            this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('成功！')</script>");

        }
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ImgSearch_Click(object sender, ImageClickEventArgs e)
        {
            Session["WaitInfoSearch"] = "";
            string searchSql = " where  SendStatus=0 ";
            if (this.txtSendDate.Text.Trim() != "")
            {
                searchSql += " and CreateDate between  " + Convert.ToDateTime(txtSendDate.Text.ToString()) + " and " + Convert.ToDateTime(txtStartDate.Text.ToString());
            }
            if (this.txtKeyWord.Text.Trim() != "")
            {
                searchSql += " and  Content like '%" + this.txtKeyWord.Text.Trim() + "%' ";
            }
            Session["WaitInfoSearch"] = searchSql;
            GetPageMore(PageIndex, 5, Session["WaitInfoSearch"].ToString());
        }
        private string getAllSelectedID()
        {
            string items = "";
            return items;
        }
        private void bianji()
        {
            int waitInfoID = 1;
            string content = "";
            TCS.Model.Weibo.WeiBo_WaitInfo waitInfo = new TCS.BLL.Weibo.WeiBo_WaitInfo().GetModel(waitInfoID);

        }
        /// <summary>
        /// 日期转换
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string ConvertToDate(object obj)
        {
            string day = Convert.ToDateTime(obj).Day.ToString();
            string month = Convert.ToDateTime(obj).Month.ToString();
            string result = "" + month + "月<span>" + day + "</span>号";
            return result;
        }

        private void BindEmotion()
        {
            this.Repeater1.DataSource = GetEmotion("心情");
            this.Repeater1.DataBind();
            this.Repeater2.DataSource = GetEmotion("休闲");
            this.Repeater2.DataBind();
            this.Repeater3.DataSource = GetEmotion("星座");
            this.Repeater3.DataBind();
            this.Repeater4.DataSource = GetEmotion("管不着");
            this.Repeater4.DataBind();
            this.Repeater5.DataSource = GetEmotion("悠嘻猴");
            this.Repeater5.DataBind();
            this.Repeater6.DataSource = GetEmotion("哈皮兔");
            this.Repeater6.DataBind();
            this.Repeater7.DataSource = GetEmotion("小新小浪");
            this.Repeater7.DataBind();
        }
        /// <summary>
        /// 获取表情
        /// </summary>
        /// <param name="type">标签类型</param>
        /// <returns></returns>
        public DataSet GetEmotion(string type)
        {
            TCS.Model.Emotion emotion = new TCS.Model.Emotion();
            string sql = "select * from dbo.emotion where category='" + type + "'";
            DataSet ds = DbHelperSQL.Query(sql);
            return ds;
        }
        public DataSet GetPageMore(int PageIndex, int pageSize, string stringWhere)
        {
            int count = PageIndex * pageSize;
            string sql = "select top " + count + " * from WeiBo_WaitInfo ";
            if (stringWhere != "")
            {
                sql += stringWhere;
            }
            DataSet ds = DbHelperSQL.Query(sql);
            return ds;
        }

        protected void btnPage_Click(object sender, EventArgs e)
        {
            PageIndex++;
            rptWaitInfo.DataSource = GetPageMore(PageIndex, 5, Session["WaitInfoSearch"].ToString());
            rptWaitInfo.DataBind();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="content"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        //[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
        //public bool ModifyWaitInfo(string content, int id)
        //{
        //    string sql = " update WeiBo_WaitInfo set Content='" + content + "' where ID=" + id;
        //    bool result = false;
        //    if (DbHelperSQL.ExecuteSql(sql) > 0)
        //    {
        //        result = true;
        //    }
        //    //this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('修改！')</script>;localtion.href='publish.aspx'");
        //    return result;
        //}
        protected void rptWaitInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton linkDelete = (LinkButton)e.Item.FindControl("linkDelete");
                linkDelete.Attributes.Add("onclick", "return confirm('确定要删除吗？')");
            }
        }

        protected void rptWaitInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            TCS.Model.Weibo.WeiBo_WaitInfo waitInfo = new TCS.Model.Weibo.WeiBo_WaitInfo();

            int id = Convert.ToInt32(e.CommandArgument.ToString());
            bool result = false;
            if (e.CommandName == "linkDelete")
            {
                result = new TCS.BLL.Weibo.WeiBo_WaitInfo().Delete(id);
                if (result == true)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('操作成功！')</script>;localtion.href='publish.aspx'");
                    BindWaitInfo();
                }
                else
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('操作失败！')</script>;localtion.href='publish.aspx'");
                    BindWaitInfo();
                }
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string itemId = "";
            foreach (RepeaterItem item in this.rptWaitInfo.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked)
                {
                    long ID = Convert.ToInt64(((HtmlInputHidden)item.FindControl("hfID")).Value);
                    // 微博删除
                    string delete = "";
                    try
                    {
                        itemId += ID + ",";
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    } 
                }
            }
            itemId = itemId.Substring(0, itemId.Length - 1);
            bool result = new TCS.BLL.Weibo.WeiBo_WaitInfo().DeleteList(itemId);
            BindWaitInfo();

        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
        public bool PicUpload()
        {
            bool flag = false;

            if (fileUpload.HasFile)
            {
                string fileContentType = fileUpload1.PostedFile.ContentType;
                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
                {
                    string name = fileUpload1.PostedFile.FileName;                  // 客户端文件路径
                    string datatime = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");  //为了防止重名，获得日期为文件名  年月日时分秒毫秒        
                    FileInfo file = new FileInfo(name);
                    string fileName = file.Name;                                    // 文件名称
                    string fileName_s = "zxq_" + datatime + "_" + file.Name;       // 缩略图文件名称
                    string webFilePath = Server.MapPath("~\\ImgUpload\\" + fileName_s);// 服务器端文件路径
                    if (!File.Exists(webFilePath))
                    {
                        try
                        {
                            fileUpload1.SaveAs(webFilePath);                  // 使用 SaveAs 方法保存文件
                            flag = true;
                            ViewState["PicPath1"] = webFilePath;      //物理路径
                            ViewState["PicPath"] = fileName_s;     // 虚拟路径
                            this.txtText.Value = "分享了图片 " + txtText.Value;
                            Label1.Text = "提示：文件“" + fileName + "”成功上传，并生成“" + fileName_s + "”文件类型为：" + fileUpload1.PostedFile.ContentType + "，文件大小为：" + fileUpload1.PostedFile.ContentLength + "B";
                        }
                        catch (Exception ex)
                        {
                            flag = false;
                            ViewState["PicPath"] = "";
                            Label1.Text = "提示：文件上传失败，失败原因：" + ex.Message;
                        }
                    }
                    else
                    {
                        flag = false;
                        ViewState["PicPath"] = "";
                        Label1.Text = "提示：文件已经存在，请重命名后上传";
                    }
                }
                else
                {
                    flag = false;
                    ViewState["PicPath"] = "";
                    Label1.Text = "提示：文件类型不符";
                }
            }
            return flag;
        }
        protected void btnUp_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile)
            {
                string fileContentType = fileUpload.PostedFile.ContentType;
                if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
                {
                    string name = fileUpload.PostedFile.FileName;                  // 客户端文件路径
                    string datatime = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");  //为了防止重名，获得日期为文件名  年月日时分秒毫秒        
                    FileInfo file = new FileInfo(name);
                    string fileName = file.Name;                                    // 文件名称
                    string fileName_s = "zxq_" + datatime + "_" + file.Name;       // 缩略图文件名称
                    string webFilePath = Server.MapPath("~\\ImgUpload\\" + fileName_s);// 服务器端文件路径
                    if (!File.Exists(webFilePath))
                    {
                        try
                        {
                            fileUpload.SaveAs(webFilePath);                  // 使用 SaveAs 方法保存文件
                            ViewState["PicPath1"] = webFilePath;      //物理路径
                            ViewState["PicPath"] = fileName_s;     // 虚拟路径
                            this.txtText.Value = "分享了图片 " + txtText.Value;
                            Label1.Text = "提示：文件“" + fileName + "”成功上传，并生成“" + fileName_s + "”文件类型为：" + fileUpload.PostedFile.ContentType + "，文件大小为：" + fileUpload.PostedFile.ContentLength + "B";
                        }
                        catch (Exception ex)
                        {
                            ViewState["PicPath"] = "";
                            Label1.Text = "提示：文件上传失败，失败原因：" + ex.Message;
                        }
                    }
                    else
                    {
                        ViewState["PicPath"] = "";
                        Label1.Text = "提示：文件已经存在，请重命名后上传";
                    }
                }
                else
                {
                    ViewState["PicPath"] = "";
                    Label1.Text = "提示：文件类型不符";
                }
            }
          
                 
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string a = "";
        }

        //protected void Button1_Click(object sender, EventArgs e)
        //{
        //    Response.Write("<script>alert('test');</script>");
        //}


    }
}
